<?php
/**
 * Created by PhpStorm.
 * User: wangjie
 * Date: 2020/6/8
 * Time: 下午5:36
 */

namespace App\Api\Controllers\EasyPay;

use App\Api\Controllers\BaseController;
use App\Common\PaySuccessAction;
use App\Models\EasypayaStore;
use App\Models\EasypayStore;
use App\Models\MerchantWalletDetail;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\RefundOrder;
use App\Models\UserWalletDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;

class NotifyController extends BaseController
{
    public function merchant_apply_notify_url(Request $request): string
    {
        $data = $request->all();
//        error_log(date('Y-m-d H:i:s') . " 【银盛进件回调】： " . json_encode([$data]) . "\n\n", 3, "/tmp/" . 'ys-add-mch' . date('Ymd') . ".log");
        Log::channel("easypay")->info("merchant_apply_notify_url", $data);

        $version= $request->get("type","easypay");

        $query=EasypayStore::query();
        if($version=="easypaya"){
            $query=EasypayaStore::query();
        }

        if ($data['auditStatus'] == "0") {
            $sysInfo = json_decode($data['sysInfo'], true);
            $config = $query->where('operaTrace', $data['operaTrace'])->first();
            if (!empty($config)) {
                $query->where('operaTrace', $data['operaTrace'])->update([
                    'termMercode' => $sysInfo[0]['termMercode'] ?? DB::raw("termMercode"),
                    'termTermcode' => $sysInfo[0]['termTermcode'] ?? DB::raw("termTermcode"),
                    'audit_status' => 0,
                    'audit_msg' => '审核通过'
                ]);
                DB::table('store_pay_ways')
                    ->where(['store_id' => $config->store_id, 'company' => $version])
                    ->update([
                        'status' => 1,
                        'status_desc' => '开通成功',
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s'),
                    ]);
            }
        } else {
            if (isset($data['operaTrace']) && !empty($data['operaTrace'])) {
                $query->where('operaTrace', $data['operaTrace'])->update(['audit_msg' => $data['auditMsg'], 'audit_status' => 1]);
            }
        }

        return json_encode([
            "version" => $data["version"],
            "clientCode" =>  $data["version"],
            "MAC" =>  $data["MAC"],
            "retCode" => "0000",
            "retMsg" =>$data["retMsg"],
        ]);
    }

    public function pay_notify_url(Request $request)
    {
        try {
            $data = $request->all();
            Log::info('易生-支付回调');
            Log::info($data);
//            $data = array (
//                '{"sign":"38F1F1B8A8C5F64BD7B6BB33C8D708E1","wxopenid":"2088012904744331","wxtimeend":"20200710151758","tradetrace":"ali_qr20200710151751159145328","clearamt":"1","wxtransactionid":"2020071022001444331430816249","acctype":"U","payamt":"1","wtorderid":"21620200710151751116234"}' => NULL,
//            );

            if (isset($data) && !empty($data) && $data['data']['finRetcode'] == '00') {

                if (isset($data['data']['oriOrgTrace'])) {
                    $out_trade_no = $data['data']['oriOrgTrace']; //商户订单号（原交易流水）
                    $trade_no = $data['data']['outTrace']; //系统订单号

                    $day = date('Ymd', time());
                    $table = 'orders_' . $day;
                    if (Schema::hasTable($table)) {
                        $order = DB::table($table)->where('out_trade_no', $out_trade_no)->first();
                    } else {
                        $order = Order::where('out_trade_no', $out_trade_no)->first();
//                        if (!$order) {
//                            $order = Order::where('trade_no', $trade_no)->first();
//                        }
                    }

                    //订单存在
                    if ($order) {
                        //系统订单未成功
                        if ($order->pay_status == '2') {
                            \App\Models\OrderExtend::create([
                                'out_trade_no' => $out_trade_no,
                                "channel_code"=>2,
                                'transactionId' => isset($data['data']['pcTrace']) ? $data['data']['pcTrace'] : '',
                                'user_bar_code' => isset($data['data']['outTrace']) ? $data['data']['outTrace'] : '',
                            ]);
                            $pay_time = date('Y-m-d H:i:s', strtotime($data['data']['timeEnd'])); //支付完成时间，格式为 yyyyMMddhhmmss，如2009年12月27日9点10分10秒表示为20091227091010
                            $buyer_pay_amount = isset($data['data']['payerAmt']) ? ($data['data']['payerAmt'] / 100) : ''; //否，实付金额，单位分
                            $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                            $buyer_id = $data['data']['payerId']; //用户在商户 appid 下的唯一标识(微信/支付宝渠道返回)
                            $in_data = [
                                'status' => '1',
                                'pay_status' => 1,
                                'pay_status_desc' => '支付成功',
                                'trade_no' => $trade_no,
                                'pay_time' => $pay_time,
                                'buyer_id' => $buyer_id,
                                'buyer_pay_amount' => $buyer_pay_amount,
                            ];

                            $this->update_day_order($in_data, $out_trade_no);

                            if (strpos($out_trade_no, 'scan')) {

                            } else {
                                //支付成功后的动作
                                $data = [
                                    'ways_type' => $order->ways_type,
                                    'company' => $order->company,
                                    'ways_type_desc' => $order->ways_type_desc,
                                    'source_type' => '21000', //返佣来源
                                    'source_desc' => '易生支付', //返佣来源说明
                                    'total_amount' => $order->total_amount,
                                    'out_trade_no' => $order->out_trade_no,
                                    'other_no' => $order->other_no,
                                    'rate' => $order->rate,
                                    'fee_amount' => $order->fee_amount,
                                    'merchant_id' => $order->merchant_id,
                                    'store_id' => $order->store_id,
                                    'user_id' => $order->user_id,
                                    'config_id' => $order->config_id,
                                    'store_name' => $order->store_name,
                                    'ways_source' => $order->ways_source,
                                    'pay_time' => $pay_time,
                                    'device_id' => $order->device_id,
                                ];
                                PaySuccessAction::action($data);
                            }
                        }
                    }
                }

                return json_encode([
                    'resultcode' => '00'
                ]);
            } else {
                Log::info('易生-支付回调-结果');
                Log::info($data);
            }

        } catch (\Exception $ex) {
            Log::info('易生支付回调-异步报错');
            Log::info($ex->getMessage() . ' | ' . $ex->getFile() . ' | ' . $ex->getLine());
        }
    }

    //易生 支付回调
    public function pay_notify_url1(Request $request)
    {
        try {
            $data = $request->all();
            Log::info('易生-支付回调');
            Log::info($data);
//            $data = array (
//                '{"sign":"38F1F1B8A8C5F64BD7B6BB33C8D708E1","wxopenid":"2088012904744331","wxtimeend":"20200710151758","tradetrace":"ali_qr20200710151751159145328","clearamt":"1","wxtransactionid":"2020071022001444331430816249","acctype":"U","payamt":"1","wtorderid":"21620200710151751116234"}' => NULL,
//            );

            if (isset($data) && !empty($data)) {
                $data = json_decode(array_keys($data)[0], true);

                if (isset($data['tradetrace'])) {
                    $out_trade_no = $data['tradetrace']; //商户订单号（原交易流水）
                    $trade_no = $data['wtorderid']; //系统订单号

                    $day = date('Ymd', time());
                    $table = 'orders_' . $day;
                    if (Schema::hasTable($table)) {
                        $order = DB::table($table)->where('out_trade_no', $out_trade_no)->first();
                    } else {
                        $order = Order::where('out_trade_no', $out_trade_no)->first();
//                        if (!$order) {
//                            $order = Order::where('trade_no', $trade_no)->first();
//                        }
                    }

                    //订单存在
                    if ($order) {
                        //系统订单未成功
                        if ($order->pay_status == '2') {
                            $pay_time = date('Y-m-d H:i:s', strtotime($data['wxtimeend'])); //支付完成时间，格式为 yyyyMMddhhmmss，如2009年12月27日9点10分10秒表示为20091227091010
                            $buyer_pay_amount = isset($data['payamt']) ? ($data['payamt'] / 100) : ''; //否，实付金额，单位分
                            $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                            $buyer_id = $data['wxopenid']; //用户在商户 appid 下的唯一标识(微信/支付宝渠道返回)
                            $in_data = [
                                'status' => '1',
                                'pay_status' => 1,
                                'pay_status_desc' => '支付成功',
                                'trade_no' => $trade_no,
                                'pay_time' => $pay_time,
                                'buyer_id' => $buyer_id,
                                'buyer_pay_amount' => $buyer_pay_amount,
                            ];

                            $this->update_day_order($in_data, $out_trade_no);

                            if (strpos($out_trade_no, 'scan')) {

                            } else {
                                //支付成功后的动作
                                $data = [
                                    'ways_type' => $order->ways_type,
                                    'company' => $order->company,
                                    'ways_type_desc' => $order->ways_type_desc,
                                    'source_type' => '21000', //返佣来源
                                    'source_desc' => '易生支付', //返佣来源说明
                                    'total_amount' => $order->total_amount,
                                    'out_trade_no' => $order->out_trade_no,
                                    'other_no' => $order->other_no,
                                    'rate' => $order->rate,
                                    'fee_amount' => $order->fee_amount,
                                    'merchant_id' => $order->merchant_id,
                                    'store_id' => $order->store_id,
                                    'user_id' => $order->user_id,
                                    'config_id' => $order->config_id,
                                    'store_name' => $order->store_name,
                                    'ways_source' => $order->ways_source,
                                    'pay_time' => $pay_time,
                                    'device_id' => $order->device_id,
                                ];
                                PaySuccessAction::action($data);
                            }
                        }
                    }
                }

                return json_encode([
                    'resultcode' => '00'
                ]);
            } else {
                Log::info('易生-支付回调-结果');
                Log::info($data);
            }

        } catch (\Exception $ex) {
            Log::info('易生支付回调-异步报错');
            Log::info($ex->getMessage() . ' | ' . $ex->getFile() . ' | ' . $ex->getLine());
        }
    }


//    //易生 (主扫支付)支付回调
//    public function pay_notify(Request $request)
//    {
//        try {
//            $data = $request->all();
//            Log::info('易生-主扫支付回调');
//            Log::info($data);
//
//            if (isset($data['ordNo'])) {
//                $out_trade_no = $data['ordNo'];
//
//                $day = date('Ymd', time());
//                $table = 'orders_' . $day;
//                if (Schema::hasTable($table)) {
//                    $order = DB::table($table)->where('out_trade_no', $out_trade_no)->first();
//                } else {
//                    $order = Order::where('out_trade_no', $out_trade_no)->first();
//                }
//
//                //订单存在
//                if ($order) {
//                    //系统订单未成功
//                    if ($order->pay_status == '2') {
//                        $trade_no = $data['transactionId'];
//                        $pay_time = date('Y-m-d H:i:s', strtotime($data['payTime']));
//                        $buyer_pay_amount = $data['amt'];
//                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
//                        $buyer_id = $data['buyerId'];
//                        $in_data = [
//                            'status' => '1',
//                            'pay_status' => 1,
//                            'pay_status_desc' => '支付成功',
//                            'trade_no' => $trade_no,
//                            'pay_time' => $pay_time,
//                            'buyer_id' => $buyer_id,
//                            'buyer_pay_amount' => $buyer_pay_amount,
//                        ];
//
//                        $this->update_day_order($in_data, $out_trade_no);
//
//                        if (strpos($out_trade_no, 'scan')) {
//
//                        } else {
//                            //支付成功后的动作
//                            $data = [
//                                'ways_type' => $order->ways_type,
//                                'company' => $order->company,
//                                'ways_type_desc' => $order->ways_type_desc,
//                                'source_type' => '21000', //返佣来源
//                                'source_desc' => '易生支付', //返佣来源说明
//                                'total_amount' => $order->total_amount,
//                                'out_trade_no' => $order->out_trade_no,
//                                'other_no' => $order->other_no,
//                                'rate' => $order->rate,
//                                'fee_amount' => $order->fee_amount,
//                                'merchant_id' => $order->merchant_id,
//                                'store_id' => $order->store_id,
//                                'user_id' => $order->user_id,
//                                'config_id' => $order->config_id,
//                                'store_name' => $order->store_name,
//                                'ways_source' => $order->ways_source,
//                                'pay_time' => $pay_time,
//                                'device_id' => $order->device_id,
//                            ];
//                            PaySuccessAction::action($data);
//                        }
//                    }
//                }
//            }
//
//            return json_encode([
//                'code' => 'success',
//                'msg' => "成功",
//            ]);
//        } catch (\Exception $ex) {
//            Log::info('易生支付回调-异步报错');
//            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
//        }
//    }


//    //易生 退款回调
//    public function refund_notify_url(Request $request)
//    {
//        try {
//            $data = $request->all();
//            Log::info('易生-退款回调');
//            Log::info($data);
//
//            if (isset($data['ordNo'])) {
//                $out_trade_no = $data['ordNo'];
//                $a = array('a', '_', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
//                $b = str_ireplace($a, "", $out_trade_no);
//                $day = substr($b, 0, 8);
//                $table = 'orders_' . $day;
//
//                $out_trade_no = substr($out_trade_no , 0, strlen($out_trade_no)-4);
//
//                if (Schema::hasTable($table)) {
//                    $order = DB::table($table)->where('out_trade_no', $out_trade_no)->first();
//                } else {
//                    $order = Order::where('out_trade_no', $out_trade_no)->first();
//                }
//
//                //订单存在
//                if ($order && $order->pay_status == '1') {
//                    if ($data['bizCode'] == '0000') {
//                        $refund_amount = $data["totalOffstAmt"];
//                        $update_data = [
//                            'status' => 6,
//                            'pay_status' => 6,
//                            'pay_status_desc' => '已退款',
//                            'refund_amount' => $order->refund_amount + $refund_amount,
//                            'fee_amount' => 0,
//                        ];
//                        if (Schema::hasTable($table)) {
//                            DB::table($table)
//                                ->where('out_trade_no', $out_trade_no)
//                                ->update($update_data);
//                        } else {
//                            Order::where('out_trade_no', $out_trade_no)
//                                ->update($update_data);
//                        }
//
//                        if (Schema::hasTable('order_items')) {
//                            OrderItem::where('out_trade_no', $out_trade_no)->update($update_data);
//                        }
//
//                        RefundOrder::create([
//                            'ways_source' => $order->ways_source,
//                            'type' => $order->ways_type,
//                            'refund_amount' => $refund_amount, //退款金额
//                            'refund_no' => $data['ordNo'], //退款单号
//                            'store_id' => $order->store_id,
//                            'merchant_id' => $order->merchant_id,
//                            'out_trade_no' => $order->out_trade_no,
//                            'trade_no' => $order->other_no
//                        ]);
//
//                        //返佣去掉
//                        UserWalletDetail::where('out_trade_no', $order->out_trade_no)->update([
//                            'settlement' => '03',
//                            'settlement_desc' => '退款订单',
//                        ]);
//                        MerchantWalletDetail::where('out_trade_no', $order->out_trade_no)->update([
//                            'settlement' => '03',
//                            'settlement_desc' => '退款订单',
//                        ]);
//                    }
//                }
//            }
//
//            return json_encode([
//                'code' => 'success',
//                'msg' => "成功",
//            ]);
//        } catch (\Exception $ex) {
//            Log::info('易生-退款异步报错');
//            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
//        }
//    }


}
